package com.scs.application.modules.design.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.scs.application.core.exceptions.BusinessException;
import com.scs.application.core.model.PageResult;
import com.scs.application.core.model.RestResult;
import com.scs.application.core.mvc.controller.BaseController;
import com.scs.application.core.mvc.controller.CrudController;
import com.scs.application.core.utils.CacheUtils;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.design.dto.CreateCRUDFileDTO;
import com.scs.application.modules.design.dto.DataViewDTO;
import com.scs.application.modules.design.dto.QueryContext;
import com.scs.application.modules.design.dto.TableColumn;
import com.scs.application.modules.design.entity.DataView;
import com.scs.application.modules.design.mapper.DataViewMapper;
import com.scs.application.modules.design.service.DataViewService;
import com.scs.application.modules.design.service.ProgramService;
import com.scs.application.modules.design.service.QueryGenerator;
import com.scs.application.modules.design.service.impl.TableDataViewServiceImpl;
import com.scs.application.modules.upms.entity.User;
import com.scs.application.modules.upms.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@Slf4j
public class DataViewController extends CrudController<DataView, String, TableDataViewServiceImpl>  {
    @Autowired
    private TableDataViewServiceImpl dataViewService;
    @Autowired
    private DataViewMapper dataViewMapper;

    @Autowired
    private ProgramService programService;

    @GetMapping(value = "/data-view/find")
    public RestResult getDataView(
            @RequestParam("viewKey") String viewKey,
            @RequestParam(name = "flowKey", defaultValue = "") String flowKey) {
        HashMap<String, Object> result = getView(viewKey, flowKey);
        if (result == null) {
            return RestResult.error("获取视图失败！");
        }
        return RestResult.ok("获取视图成功！", result);
    }
    @GetMapping(value = "/data-view/findCache")
    public RestResult findCache(
            @RequestParam("viewKey") String viewKey) {
        String dataViewString = CacheUtils.get(CacheUtils.DATAVIEW_CACHE, viewKey) + "";
        if (dataViewString.length() < 1) {
            return null;
        }
        JSONObject jsonDataView = JSONObject.parseObject(dataViewString);
        return RestResult.ok("获取视图成功！", jsonDataView);
    }

    @RequestMapping(value = "/program/dict/list", method = RequestMethod.GET)
    public RestResult getDictList() {
        BusinessException.throwError("方法已废弃");
        HashMap<String, Object> result = new HashMap<String, Object>();
        return RestResult.ok("获取字典成功！", result);
    }

    @RequestMapping(value = "/program/data-view/list", method = RequestMethod.GET)
    public RestResult getDataViewList() {
        return RestResult.ok("获取视图成功！", dataViewService.list());
    }

    @RequestMapping(value = "/program/data-view/delete", method = RequestMethod.DELETE)
    public RestResult deleteDataView(@RequestBody Map<String, Object> para) {
        List<Serializable> ids = (List<Serializable>) para.get("ids");
        String viewKey = ids.get(0).toString();
        dataViewService.deleteView(viewKey);
        return RestResult.ok("删除视图成功！") ;
    }

    @RequestMapping(value = "/program/table-columns", method = RequestMethod.GET)
    public RestResult tableSchema(@RequestParam String tableName) {
//        BusinessException.throwError("方法已废弃");
        List<TableColumn> models = dataViewMapper.getTableColumns(tableName);

        return RestResult.ok("获取表格列信息成功！",models);
    }

    @RequestMapping(value = "/program/data-view/save", method = RequestMethod.POST)
    public RestResult saveDataView(@RequestBody JSONObject dataViewJson) {
        return RestResult.ok("保存视图成功！", dataViewService.saveView(dataViewJson));
    }

    @RequestMapping(value = "/program/data-view/listObjs", method = RequestMethod.GET)
    public RestResult listObjs() {
        List<String> viewKeyList = dataViewService.list(Wrappers.<DataView>query().select("view_key")).stream().map(DataView::getViewKey).collect(Collectors.toList());
        HashMap<String, Object> viewMap = new HashMap<String, Object>();
        if (viewKeyList != null && viewKeyList.size() > 0) {
            for (String viewKey : viewKeyList) {
                try {
                    viewMap.put(viewKey, JSONObject.parseObject(CacheUtils.get(CacheUtils.DATAVIEW_CACHE, viewKey) + ""));
                } catch (Exception ex) {
                    log.error(ex.getMessage());
                }
            }
        }
        return RestResult.ok("获取成功！", viewMap);
    }

    /**
     * 根据视图Key和流程Key获取相关视图和流程信息
     *
     * @param viewKey
     * @param flowKey
     * @return
     */
    private HashMap<String, Object> getView(String viewKey, String flowKey) {
        HashMap<String, Object> result = new HashMap<>();

        String dataViewString = CacheUtils.get(CacheUtils.DATAVIEW_CACHE, viewKey) + "";
        if (dataViewString.length() < 1) {
            return null;
        }
        JSONObject jsonDataView = JSONObject.parseObject(dataViewString);
        result.put("view", jsonDataView);
        return result;
    }


//    /**
//     * 选择 获取数据列表
//     */
//    @GetMapping("/program/data-view/page")
//    public PageResult pageForSelect(HttpServletRequest request) {
//        IPage<DataView>  page = new Page();
//
//        QueryGenerator.initQueryWrapper(request);
//
////        queryContext.getWrapper().select("id,view_key,view_name,module_name,description,view_type,modifier,gmt_modified");
//        IPage pageResult = dataViewService.page(page);
//        return PageResult.ok("查询成功", pageResult.getRecords(), pageResult.getTotal());
//    }


    @GetMapping("/program/data-view/page")
    public PageResult pageCustom(HttpServletRequest request) {
        return super.pageCommon(request, new DataView());
    }

    @RequestMapping(value = "/program/create-all", method = RequestMethod.POST)
    public RestResult createAll(@RequestBody CreateCRUDFileDTO createCRUDFileDTO) {
        programService.createAll(createCRUDFileDTO);
        return RestResult.ok("生成文件完成！");
    }
}
